package com.zhida.jiyangcenter.mian.fragment

import android.app.AlertDialog
import android.app.ExpandableListActivity
import android.content.DialogInterface
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.flyco.animation.BounceEnter.BounceTopEnter
import com.flyco.animation.SlideExit.SlideBottomExit
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.WebActivity
import com.zhida.jiyangcenter.WebNoTokenActivity
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.mian.ArchivesDetailsActivity
import com.zhida.jiyangcenter.mian.AssessmentActivity
import com.zhida.jiyangcenter.mian.BaseFragment
import com.zhida.jiyangcenter.mian.PayArchivesActivity
import com.zhida.jiyangcenter.modle.EquipmentListActivity
import com.zhida.jiyangcenter.modle.UpdataReportActivity
import com.zhida.jiyangcenter.utils.*
import com.zhida.jiyangcenter.widget.WaterModel
import kotlinx.android.synthetic.main.fragment_main_archives.*

@ContentLayout(R.layout.fragment_main_archives)
class MainArchivesFragment : BaseFragment() {
    override fun getTitle(): String {
        return "档案"
    }

    val mModelList = ArrayList<WaterModel>().apply {
        add(WaterModel("心率"))
        add(WaterModel("血糖"))
        add(WaterModel("步数"))
        add(WaterModel("疲劳"))
        add(WaterModel("睡眠"))
        add(WaterModel("热量"))

    }
    val yundongAdapter = Adapter()
    val tiaoliAdapter = TiaoliAdapter()
    val shanshiAdapter = ShanshiAdapter()
    val yingyangAdapter = YingyangAdapter()
    val shuimianAdapter = ShuimianAdapter()
    val fanganAdapter=FanganAdapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        super.initConfig(savedInstanceState)
        refresh_layout.setOnRefreshListener {
            getData()
        }
        view_status_bar.updateLayoutParams<ConstraintLayout.LayoutParams> {
            height = getStatusBarHeight()
        }
        niv_main_archives_head.post {
            custom_view.setModelList(mModelList, niv_main_archives_bg)
        }
        rv_left_yundong.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_left_yundong.adapter = yundongAdapter
        yundongAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_archives_right_shanshi -> {
                    if (yingyangAdapter.data[position].state == "0") {
                        val et = EditText(context)
                        et.inputType = InputType.TYPE_CLASS_NUMBER
                        et.filters = arrayOf(
                            FilterUtil.getInputFilter(
                                requireContext(),
                                "不支持输入表情或者特殊符号", FilterUtil.MATCHER_DEFAULT
                            ), InputFilter.LengthFilter(12)
                        )
                        AlertDialog.Builder(context).setTitle("请输入消息")
                            .setIcon(android.R.drawable.sym_def_app_icon)
                            .setView(et)
                            .setPositiveButton("确定") { dialog, which ->
                                //按下确定键后的事件
                                dialog.dismiss()
                                lifecycleScope.request({
                                    APIPay.service()
                                        .exerciseUpdate(
                                            yundongAdapter.data[position].exercise_record_id.toString(),
                                            et.text.toString()
                                        )
                                }, object : BaseAPI<Any>() {
                                    override fun onSuccess(t: Any?, state: Int, msg: String) {
                                        tipSuccess(msg)
                                        getData()
                                    }

                                    override fun onError(e: APIException) {
                                        tipFail(e.eMessage)
                                    }

                                })
                            }.setNegativeButton("取消", null).show()
                    }
                }
            }
        }
        rv_left_tiaoli.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_left_tiaoli.adapter = tiaoliAdapter
        rv_left_shanshi.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_left_shanshi.adapter = shanshiAdapter
        shanshiAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_archives_right_shanshi -> {
                    if (shanshiAdapter.data[position].state == "0")
                        lifecycleScope.request({
                            APIPay.service()
                                .mealsUpdate(shanshiAdapter.data[position].meals_record_id.toString())
                        }, object : BaseAPI<Any>() {
                            override fun onSuccess(t: Any?, state: Int, msg: String) {
                                tipSuccess(msg)
                                getData()
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                        })
                }
            }
        }
        rv_left_yingyang.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_left_yingyang.adapter = yingyangAdapter
        yingyangAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_archives_right_shanshi -> {
                    if (yingyangAdapter.data[position].state == "0")
                        lifecycleScope.request({
                            APIPay.service()
                                .nutritionUpdate(yingyangAdapter.data[position].nutrition_record_id.toString())
                        }, object : BaseAPI<Any>() {
                            override fun onSuccess(t: Any?, state: Int, msg: String) {
                                tipSuccess(msg)
                                getData()
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                        })
                }
            }
        }
        rv_left_shuimian.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_left_shuimian.adapter = shuimianAdapter
        shuimianAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_archives_right_shanshi -> {
                    if (shuimianAdapter.data[position].state == "0") {
                        val et = EditText(context)
                        et.filters = arrayOf(
                            FilterUtil.getInputFilter(
                                requireContext(),
                                "不支持输入表情或者特殊符号", FilterUtil.MATCHER_DEFAULT
                            ), InputFilter.LengthFilter(2)
                        )
                        et.inputType = InputType.TYPE_CLASS_NUMBER
                        AlertDialog.Builder(context).setTitle("请输入消息")
                            .setIcon(android.R.drawable.sym_def_app_icon)
                            .setView(et)
                            .setPositiveButton("确定") { dialog, which ->
                                //按下确定键后的事件
                                dialog.dismiss()
                                lifecycleScope.request({
                                    APIPay.service()
                                        .sleepUpdate(
                                            shuimianAdapter.data[position].sleep_record_id.toString(),
                                            et.text.toString()
                                        )
                                }, object : BaseAPI<Any>() {
                                    override fun onSuccess(t: Any?, state: Int, msg: String) {
                                        tipSuccess(msg)
                                        getData()
                                    }

                                    override fun onError(e: APIException) {
                                        tipFail(e.eMessage)
                                    }

                                })
                            }.setNegativeButton("取消", null).show()
                    }
                }
            }
        }
        glideImage(niv_main_archives_head, SP.avatar_path.get())
        tv_main_archives_name.text = SP.nickname.get() ?: SP.account.get().toString()

        iv_archives_consultation.setOnClickListener {
            startActivity<UpdataReportActivity> { }
        }
        iv_archives_assessment.setOnClickListener {
            startActivity<WebActivity> {
                putExtra(
                    WebActivity.URL,
                    "http://beauty.hebzd.com/media/healthDocument.html"
                )
                putExtra(WebActivity.TITLE, "电子健康档案")
            }
        }
        iv_archives_archives.setOnClickListener {
            startActivity<EquipmentListActivity> { }
        }
        getData()
        tv_main_archives_jindu.setOnClickListener {
            createFangan()
        }

        rv_fangan.layoutManager=object :LinearLayoutManager(context){
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_fangan.addItemDecoration( HorizontalDividerItemDecoration.Builder(requireContext()).sizeResId(R.dimen.dividerBig)
            .colorResId(R.color.colorBack).build())
        rv_fangan.adapter=fanganAdapter
        fanganAdapter.setOnItemClickListener { _, view, position ->
            startActivity<ArchivesDetailsActivity> {
                putExtra("uuid",fanganAdapter.data[position].uuid)
            }
        }

        tv_commit.setOnClickListener {
            startActivity<PayArchivesActivity> {
                putExtra("orderCode",managementListEntity.uuid)
                putExtra("total_money",managementListEntity.price)
                putExtra("kind","7")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    fun createFangan() {
        lifecycleScope.request({APIHealth.service().documentTestExamination()},object :BaseAPI<DocumentTestExaminationEntity>(){
            override fun onSuccess(t: DocumentTestExaminationEntity?, state: Int, msg: String) {
                when {
                    t?.e_record!="1"->{
                        val dialog = NormalDialog(context)
                        dialog.content("您还没有填写健康档案是否去填写？")
                            .style(NormalDialog.STYLE_TWO)//
                            .title("温馨提示")
                            .btnNum(2)
                            .btnTextColor(
                                resColor(R.color.colorAccent),
                                resColor(R.color.colorAccent)
                            )
                            .btnText("是", "否")
                            .titleTextSize(23f)
                            .showAnim(BounceTopEnter())
                            .dismissAnim(SlideBottomExit())
                            .show()
                        dialog.setOnBtnClickL(OnBtnClickL {
                            dialog.dismiss()
                            startActivity<WebActivity> {
                                putExtra(
                                    WebActivity.URL,
                                    "http://beauty.hebzd.com/media/healthDocument.html"
                                )
                                putExtra(WebActivity.TITLE, "电子健康档案")
                            }
                        }, OnBtnClickL {
                            dialog.dismiss()
                        })
                    }
                    t.intelligence_test!="1"->{
                        val dialog = NormalDialog(context)
                        dialog.content("您还没有进行智能评估，是否进行测试？")
                            .style(NormalDialog.STYLE_TWO)//
                            .title("温馨提示")
                            .btnNum(2)
                            .btnTextColor(
                                resColor(R.color.colorAccent),
                                resColor(R.color.colorAccent)
                            )
                            .btnText("是", "否")
                            .titleTextSize(23f)
                            .showAnim(BounceTopEnter())
                            .dismissAnim(SlideBottomExit())
                            .show()
                        dialog.setOnBtnClickL(OnBtnClickL {
                            dialog.dismiss()
                            startActivity<AssessmentActivity> { }
                        }, OnBtnClickL {
                            dialog.dismiss()
                        })
                    }
                    t.examination!="1"->{
                        val dialog = NormalDialog(context)
                        dialog.content("您还没有上传您的体检报告，是否上传？")
                            .style(NormalDialog.STYLE_TWO)//
                            .title("温馨提示")
                            .btnNum(2)
                            .btnTextColor(
                                resColor(R.color.colorAccent),
                                resColor(R.color.colorAccent)
                            )
                            .btnText("去上传", "直接生成")
                            .titleTextSize(23f)
                            .showAnim(BounceTopEnter())
                            .dismissAnim(SlideBottomExit())
                            .show()
                        dialog.setOnBtnClickL(OnBtnClickL {
                            dialog.dismiss()
                            startActivity<UpdataReportActivity> { }
                        }, OnBtnClickL {
                            dialog.dismiss()
                            managementAdd()
                        })
                    }
                    else->managementAdd()
                }
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })

    }

    private fun managementAdd() {
        lifecycleScope.request({APIHealth.service().managementAdd()},object :BaseAPI<Any>(){
            override fun onSuccess(t: Any?, state: Int, msg: String) {
                tipSuccess("我们将会在一个工作日内为您生成专属个人健康管理方案,请您耐心等待哦")
                tv_main_archives_jindu.gone()
                tv_main_archives_tishi.visible()
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })
    }
    lateinit var managementListEntity:ManagementListEntity

    private fun getData() {
        lifecycleScope.request(
            { APIPay.service().healthTestUserData() },
            object : BaseAPI<HealthTestUserDataEntity>() {
                override fun onSuccess(t: HealthTestUserDataEntity?, state: Int, msg: String) {
                    refresh_layout.finishRefresh()
                    tv_main_archives_score.text = t?.grade
                    tv_main_archives_unscramble.text = "医师解读：" + t?.constitution
                    tv_main_archives_unscramble.setOnClickListener {
                        startActivity<WebNoTokenActivity> {
                            putExtra(WebNoTokenActivity.URL, t?.url.toString())
                            putExtra(WebNoTokenActivity.TITLE, "医师解读")
                        }
                    }
                }

                override fun onError(e: APIException) {
                    refresh_layout.finishRefresh()
                    tipFail(e.eMessage)
                }

            })
        lifecycleScope.request({APIHealth.service().managementList()},object :BaseAPI<ManagementListEntity>(){
            override fun onSuccess(t: ManagementListEntity?, state: Int, msg: String) {
                if (t!=null){
                    managementListEntity=t
                    tv_main_archives_jindu.gone()
                    tv_main_archives_tishi.visible()
                    if (!t.scheme.isNullOrEmpty()){
                        tv_main_archives_tishi.gone()
                        tv_main_archives_tips.visible()
                        if (t.state=="1") {
                            tv_commit.visible()
                        }else{
                            tv_commit.gone()
                        }
                        rv_fangan.visible()
                        fanganAdapter.setNewData(t.scheme)
                        tv_commit.text="共计：${t?.price}元   去支付"
                    }
                }
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })

//        lifecycleScope.request({ APIFile.service().home() }, object : BaseAPI<FileHomeEntity>() {
//            override fun onSuccess(t: FileHomeEntity?, state: Int, msg: String) {
//                refresh_layout.finishRefresh()
////                tv_main_archives_jindu.text = "今日已完成${t?.total_percent}%"
//                if (isAnswer){
//                    tv_commit.visible()
//                    tv_main_archives_tips.visible()
//                    tv_main_archives_jindu.gone()
//                    tv_main_archives_tishi.gone()
//                    if (!t?.exercise.isNullOrEmpty()) {
//                        cl_yundong.visible()
//                        tv_item_archives_jindu_yundong.text =
//                            t!!.exercise!![t.exercise!!.size - 1].percent.toString() + "%"
//                        t.exercise.removeAt(t.exercise.size - 1)
//                        yundongAdapter.setNewData(t.exercise)
//                    } else {
//                        cl_yundong.gone()
//                    }
//
//                    if (!t?.nurse.isNullOrEmpty()) {
//                        cl_tiaoli.visible()
//                        tv_item_archives_jindu_tiaoli.text =
//                            t!!.nurse!![t.nurse!!.size - 1].percent.toString() + "%"
//                        t.nurse.removeAt(t.nurse.size - 1)
//                        tiaoliAdapter.setNewData(t.nurse)
//                    } else {
//                        cl_tiaoli.gone()
//                    }
//                    if (!t?.meals.isNullOrEmpty()) {
//                        cl_shanshi.visible()
//                        tv_item_archives_jindu_shanshi.text =
//                            t!!.meals!![t.meals!!.size - 1].percent.toString() + "%"
//                        t.meals.removeAt(t.meals.size - 1)
//                        shanshiAdapter.setNewData(t.meals)
//                    } else {
//                        cl_shanshi.gone()
//                    }
//                    if (!t?.nutrition.isNullOrEmpty()) {
//                        cl_yingyang.visible()
//                        tv_item_archives_jindu_yingyang.text =
//                            t!!.nutrition!![t.nutrition!!.size - 1].percent.toString() + "%"
//                        t.nutrition.removeAt(t.nutrition.size - 1)
//                        yingyangAdapter.setNewData(t.nutrition)
//                    } else {
//                        cl_yingyang.gone()
//                    }
//                    if (!t?.sleep.isNullOrEmpty()) {
//                        cl_shuimian.visible()
//                        tv_item_archives_jindu_shuimian.text =
//                            t!!.sleep!![t.sleep!!.size - 1].percent.toString() + "%"
//                        t.sleep.removeAt(t.sleep.size - 1)
//                        shuimianAdapter.setNewData(t.sleep)
//                    } else {
//                        cl_shuimian.gone()
//                    }
//                }else{
//                    cl_shuimian.gone()
//                    cl_yingyang.gone()
//                    cl_shanshi.gone()
//                    cl_tiaoli.gone()
//                    cl_yundong.gone()
//                    tv_commit.gone()
//                    tv_main_archives_tips.gone()
//                    tv_main_archives_jindu.visible()
//                }
//
//            }
//
//            override fun onError(e: APIException) {
//                refresh_layout.finishRefresh()
//                tipFail(e.eMessage)
//            }
//        })
    }

    class FanganAdapter:BaseQuickAdapter<ManagementListEntity.Scheme,BaseViewHolder>(R.layout.item_fangan){
        override fun convert(helper: BaseViewHolder, item: ManagementListEntity.Scheme?) {
            glideImage(helper.getView(R.id.iv_item_archives_yundong),item?.pic?:"")
            helper.setText(R.id.tv_item_archives_type_yundong,item?.classes)
                .setText(R.id.tv_context,item?.content)
        }

    }
    class Adapter :
        BaseQuickAdapter<FileHomeEntity.Exercise, BaseViewHolder>(R.layout.item_main_archives) {
        override fun convert(helper: BaseViewHolder, item: FileHomeEntity.Exercise?) {
            helper.setText(
                R.id.tv_item_archives_left_shanshi,
                item?.name + "  " + item?.amount.toString() + item?.unit
            )
                .setText(
                    R.id.tv_item_archives_right_shanshi,
                    if (item?.state == "0") "点击完成" else "已完成"
                )
                .addOnClickListener(R.id.tv_item_archives_right_shanshi)
        }

    }

    class TiaoliAdapter :
        BaseQuickAdapter<FileHomeEntity.Nurse, BaseViewHolder>(R.layout.item_main_archives) {
        override fun convert(helper: BaseViewHolder, item: FileHomeEntity.Nurse?) {
            helper.setText(
                R.id.tv_item_archives_left_shanshi,
                item?.name + "     " + item?.amount.toString() + item?.unit
            )
                .setText(R.id.tv_item_archives_right_shanshi, item?.amount.toString() + item?.unit)
        }

    }

    class ShanshiAdapter :
        BaseQuickAdapter<FileHomeEntity.Meal, BaseViewHolder>(R.layout.item_main_archives) {
        override fun convert(helper: BaseViewHolder, item: FileHomeEntity.Meal?) {
            helper.setText(
                R.id.tv_item_archives_left_shanshi,
                item?.name + "  " + item?.amount.toString() + item?.unit
            )
                .setText(
                    R.id.tv_item_archives_right_shanshi,
                    if (item?.state == "0") "点击完成" else "已完成"
                )
                .addOnClickListener(R.id.tv_item_archives_right_shanshi)
        }

    }

    class YingyangAdapter :
        BaseQuickAdapter<FileHomeEntity.Nutrition, BaseViewHolder>(R.layout.item_main_archives) {
        override fun convert(helper: BaseViewHolder, item: FileHomeEntity.Nutrition?) {
            helper.setText(
                R.id.tv_item_archives_left_shanshi,
                item?.name + "  " + item?.amount.toString() + item?.unit
            )
                .setText(
                    R.id.tv_item_archives_right_shanshi,
                    if (item?.state == "0") "点击完成" else "已完成"
                )
                .addOnClickListener(R.id.tv_item_archives_right_shanshi)
        }

    }

    class ShuimianAdapter :
        BaseQuickAdapter<FileHomeEntity.Sleep, BaseViewHolder>(R.layout.item_main_archives) {
        override fun convert(helper: BaseViewHolder, item: FileHomeEntity.Sleep?) {
            helper.setText(
                R.id.tv_item_archives_left_shanshi,
                item?.name + "  " + item?.amount.toString() + item?.unit
            )
                .setText(
                    R.id.tv_item_archives_right_shanshi,
                    if (item?.state == "0") "点击完成" else "已完成"
                )
                .addOnClickListener(R.id.tv_item_archives_right_shanshi)
        }

    }

}